<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="业主单位" prop="ownerUnit">
              <el-input v-model="queryParams.ownerUnit" placeholder="请输入业主单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目区域" prop="projectRegion">
              <el-input v-model="queryParams.projectRegion" placeholder="请输入项目区域" clearable @keyup.enter="handleQuery" style="width: 240px" />
            </el-form-item>
            <el-form-item label="执行总裁" prop="presidentsId">
              <el-select
                :model-value="selectedSearchPresident ? selectedSearchPresident.userName || selectedSearchPresident.nickName : ''"
                placeholder="请选择执行总裁"
                style="width: 240px"
                clearable
                @click="showSearchPresidentSelector = true"
                @clear="clearSearchPresident"
              >
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchPresidentSelector = true"> 选择执行总裁 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="操作状态" prop="operStatus">
              <el-select v-model="queryParams.operStatus" placeholder="请选择操作状态" clearable style="width: 240px">
                <el-option v-for="dict in sys_common_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="操作类型" prop="operType">
              <el-select v-model="queryParams.operType" placeholder="请选择操作类型" clearable style="width: 240px">
                <el-option v-for="dict in sys_oper_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="操作时间" prop="operTime" style="width: 308px">
              <el-date-picker
                v-model="dateRangeOperTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item style="margin-left: auto">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['project:contract:logExport']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="proContractList" border>
        <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
        <el-table-column label="合同名称" align="center" prop="contractName" show-overflow-tooltip />
        <el-table-column label="合同编号" align="center" prop="contractNumber" show-overflow-tooltip />
        <el-table-column label="业主单位" align="center" prop="ownerUnit" show-overflow-tooltip />
        <el-table-column label="项目区域" align="center" prop="projectRegionName" show-overflow-tooltip />
        <el-table-column label="执行总裁" align="center" prop="presidentsName" show-overflow-tooltip />
        <el-table-column label="合同签订时间" align="center" prop="conSignTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.conSignTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同金额" align="center" prop="conAmount">
          <template #default="scope">
            <span v-if="scope.row.conAmount">{{
              Number(scope.row.conAmount).toLocaleString('zh-CN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
              })
            }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作人" align="center" prop="operName" show-overflow-tooltip />
        <el-table-column label="操作时间" align="center" prop="operTime" width="180">
          <template #default="scope">
            <span>{{ scope.row.operTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作类型" align="center" prop="operType" width="120">
          <template #default="scope">
            <dict-tag :options="sys_oper_type" :value="scope.row.operType" />
          </template>
        </el-table-column>
        <el-table-column label="操作状态" align="center" prop="operStatus" width="120">
          <template #default="scope">
            <dict-tag :options="sys_common_status" :value="scope.row.operStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handlePreview(scope.row)">详情</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :page-sizes="[50, 100, 150, 200]"
        @pagination="getList"
      />
    </el-card>
    <el-dialog title="合同详情" v-model="showContractDetail" width="900px" append-to-body>
      <template #default>
        <div style="padding: 20px 0 20px 24px; padding-right: 24px">
          <el-form :model="currentContract" label-width="140px" label-position="left" style="width: 100%">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="合同名称">
                  <el-input v-model="currentContract.contractName" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同编号">
                  <el-input v-model="currentContract.contractNumber" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="业主单位">
                  <el-input v-model="currentContract.ownerUnit" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目区域">
                  <el-input v-model="currentContract.projectRegionName" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目执行总裁">
                  <el-input v-model="currentContract.presidentsName" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同签订时间">
                  <el-input v-model="currentContract.conSignTime" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同约定工期">
                  <el-input v-model="currentContract.conPeriod" type="textarea" :rows="4" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同预计结束时间">
                  <el-input v-model="currentContract.conEndTime" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同约定工作内容">
                  <el-input v-model="currentContract.conWorkContent" type="textarea" :rows="6" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目约定质量标准">
                  <el-input v-model="currentContract.conQualityStandard" type="textarea" :rows="6" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同总金额">
                  <el-input v-model="currentContract.conAmount" style="width: 100%" readonly>
                    <template #append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同金额备注">
                  <el-input v-model="currentContract.conAmountRemark" type="textarea" :rows="3" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="付款方式">
                  <el-input v-model="currentContract.paymentMethod" type="textarea" :rows="6" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同是否有延期约定">
                  <dict-tag :options="contract_extension" :value="currentContract.hasExtension" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="是否逾期">
                  <dict-tag :options="contract_is_delay" :value="currentContract.isDelay" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同延期约定内容">
                  <el-input v-model="currentContract.extensionContent" type="textarea" :rows="4" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注">
                  <el-input v-model="currentContract.remark" type="textarea" :rows="4" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showContractDetail = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 搜索条件用的总裁选择器 -->
    <UserSelector
      v-model:visible="showSearchPresidentSelector"
      title="选择执行总裁"
      :selected-user-ids="queryParams?.presidentsId"
      :selected-user-names="selectedSearchPresidentName"
      :multiple="false"
      @confirmWithIds="handleSearchPresidentConfirm"
      @cancel="handleSearchPresidentCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { logListProContract } from '@/api/project/init/contract';
import type { ProContractVO } from '@/api/project/init/contract/types';
import { useRoute } from 'vue-router';

const { proxy } = getCurrentInstance() as any;

const proContractList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const route = useRoute();
const total = ref(0);
const queryFormRef = ref();
const dateRangeOperTime = ref(['', '']);

const searchRegionOptions = ref([]); // 保留但不再使用
const showSearchPresidentSelector = ref(false);
const selectedSearchPresident = ref(null);
const selectedSearchPresidentName = ref('');
const showContractDetail = ref(false);
const currentContract = ref<ProContractVO>({
  id: '',
  contractName: '',
  contractNumber: '',
  ownerUnit: '',
  projectRegion: '',
  projectRegionName: '',
  presidentsId: '',
  presidentsName: '',
  conSignTime: '',
  conPeriod: '',
  conEndTime: '',
  conWorkContent: '',
  conQualityStandard: '',
  conAmount: '',
  conAmountRemark: '',
  paymentMethod: '',
  hasExtension: '',
  splitStatus: '',
  isDelay: '',
  extensionContent: '',
  remark: '',
  createBy: '',
  createTime: '',
  contractStatus: ''
});

const { sys_oper_type, contract_extension, contract_status, contract_is_delay, sys_common_status } = toRefs<any>(
  proxy?.useDict('sys_oper_type', 'contract_extension', 'contract_status', 'contract_is_delay', 'sys_common_status')
);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    id: undefined,
    contractName: '',
    ownerUnit: '',
    presidentsId: '',
    projectRegion: '',
    operType: '',
    operStatus: '',
    params: {}
  }
});
const { queryParams } = toRefs(data);

const clearSearchPresident = () => {
  selectedSearchPresident.value = null;
  selectedSearchPresidentName.value = '';
  if (queryParams.value) {
    queryParams.value.presidentsId = '';
  }
};

const handleSearchPresidentConfirm = (data) => {
  if (data.users && data.users.length > 0) {
    selectedSearchPresident.value = data.users[0];
    selectedSearchPresidentName.value = data.userNames || '';
    if (queryParams.value) {
      queryParams.value.presidentsId = data.userIds || '';
    }
  } else {
    selectedSearchPresident.value = null;
    selectedSearchPresidentName.value = '';
    if (queryParams.value) {
      queryParams.value.presidentsId = '';
    }
  }
  showSearchPresidentSelector.value = false;
};

const handleSearchPresidentCancel = () => {
  showSearchPresidentSelector.value = false;
};

const handleExport = () => {
  proxy?.download(
    'pro/contract/logList/export',
    {
      ...queryParams.value
    },
    `pro_contract_log_${new Date().getTime()}.xlsx`
  );
};

const handlePreview = (row: Partial<ProContractVO>) => {
  currentContract.value = { ...currentContract.value, ...row };
  showContractDetail.value = true;
};

const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    proxy?.addDateRange(params, dateRangeOperTime.value, 'OperTime');
    // 如果contractId不为0，强制加id和operType=2
    if (route.params.contractId && route.params.contractId !== '0') {
      params.id = route.params.contractId;
      params.operType = '2';
    }
    const res = await logListProContract(params);
    proContractList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  dateRangeOperTime.value = ['', ''];
  selectedSearchPresident.value = null;
  selectedSearchPresidentName.value = '';
  queryFormRef.value?.resetFields();
  queryParams.value.presidentsId = '';
  queryParams.value.projectRegion = '';
  queryParams.value.operType = '';
  queryParams.value.operStatus = '';
  queryParams.value.params = {};
  handleQuery();
};

onMounted(() => {
  // contractId为0时展示搜索栏，不为0时隐藏
  if (route.params.contractId && route.params.contractId !== '0') {
    showSearch.value = false;
  } else {
    showSearch.value = true;
  }
  getList();
});
</script>
